/**
 * 角色页面
 */

import { Button, Col, Flex, Form, Input, Modal, Row, Space, Table } from "antd";
import { BaseContiner, TableContainer, TableHeader } from "../../../csscomponents/base";
import { useForm } from "antd/es/form/Form";
import { useCallback, useRef, useState } from "react";
import { ISysRole, ISysRoleSearchParams, useDeletedSysRoleById, useGetSysRoleSearch } from "../../../service/sys-role-service";
import {
    PlusOutlined
} from '@ant-design/icons';
import { ErrorBox } from "../../../components/error-box";
import SysRoleForm from "./sys-role-form";
import { IFormRef } from "../../../types";
const SysRolePage = () => {
    const defaultQueryParams: ISysRoleSearchParams = {
        sysRoleName: "",
        page: 1,
        limit: 10
    }
    const [queryForm] = useForm();
    const [open, setOpen] = useState<boolean>(false)
    const sysRoleFormRef = useRef<IFormRef>();
    // 当前修改的角色
    const [updateSysRole, setUpdateSysRole] = useState<ISysRole>();
    /**
     * 搜索参数
     */
    const [queryParams, setQueryParams] = useState<ISysRoleSearchParams>(defaultQueryParams)

    /**
     * 重置方法
     */
    const resetQueryParams = () => {
        queryForm.resetFields();
        setQueryParams(defaultQueryParams);
    }
    /**
    * 搜索角色列表Handler
    * @param values 搜索参数
    */
    const onFinish = (values: { sysRoleName: string }) => {
        setQueryParams({
            ...queryParams,
            sysRoleName: values.sysRoleName,
            page: 1,
            limit: 10
        })
    }

    /**删除角色 */
    const removeSysRoleHandler = (sysRoleId: number) => {
        Modal.confirm({
            title: '⚠️警告',
            content: '你确认执行改操作吗?',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                await deleteSysRoleMutation({ sysRoleId });
                refetch();
            },
        });
    };


    const openFn = useCallback((open: boolean) => {
        setOpen(open)
    }, [])

    /**
     * !获取角色列表Hook
     */
    const { isLoading, isError, data: dataSource, error, refetch } = useGetSysRoleSearch(queryParams);

    /**
     * !删除角色HOOK
     */
    const { mutateAsync: deleteSysRoleMutation, isLoading: DIsLoading } = useDeletedSysRoleById();

    /**
     * 分页配置
     */
    const paginationProps = {
        total: dataSource?.count,
        pageSize: queryParams.limit,
        current: queryParams.page,
        showTotal: (count: number) => {
            return `共 ${count} 条`;
        },
        onChange: (pageNum: number) => {
            setQueryParams({ ...queryParams, page: pageNum });
        },
    };
    const columns = [
        {
            title: '角色ID',
            dataIndex: 'sysRoleId',
            key: 'sysRoleId',
        },
        {
            title: '角色名称',
            dataIndex: 'sysRoleName',
            key: 'sysRoleName',
        },
        {
            title: '角色权限',
            dataIndex: 'sysRolePermisstion',
            render() {
                return (
                    <a>查看</a>
                )
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
        },
        {
            title: '更多操作',
            render(project: ISysRole) {
                return (
                    <div>
                        <Button
                            style={{ marginRight: '1.2rem' }}
                            onClick={() => {
                                setUpdateSysRole(project);
                                setOpen(true);
                            }}
                        >
                            修改
                        </Button>
                        <Button
                            loading={DIsLoading}
                            danger
                            onClick={() => removeSysRoleHandler(project.sysRoleId)}
                        >
                            删除
                        </Button>
                    </div>
                );
            },
        },
    ];

    return <BaseContiner>
        <TableHeader>
            <Form
                form={queryForm}
                style={{ width: '100%' }}
                name="sys_role_search_form"
                onFinish={onFinish}
                autoComplete="off"
            >
                <Row gutter={16}>
                    <Col span={10}>
                        <Form.Item label="角色名称" name="sysRoleName" >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={10}>
                        <Form.Item >
                            <Space>
                                <Button type="primary" htmlType="submit">
                                    搜索
                                </Button>
                                <Button type="primary" onClick={() => resetQueryParams()}>
                                    重置
                                </Button>
                            </Space>
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Flex gap="small" justify="flex-end">
                            <Button type="primary" icon={<PlusOutlined />} onClick={() => {
                                if (sysRoleFormRef.current?.reset) {
                                    sysRoleFormRef.current?.reset();
                                }
                                setUpdateSysRole(undefined)
                                setOpen(true);
                            }}>
                                添加
                            </Button>
                        </Flex>
                    </Col>
                </Row>
            </Form>
        </TableHeader>
        <TableContainer>
            {isError ? (
                <ErrorBox error={error as { message: string }} />
            ) : (
                <Table
                    rowSelection={{ type: 'checkbox' }}
                    pagination={paginationProps}
                    dataSource={dataSource?.list}
                    columns={columns}
                    loading={isLoading}
                    rowKey={(row) => row?.sysRoleId}
                />
            )}
        </TableContainer>
        <SysRoleForm open={open} onRef={sysRoleFormRef} refetch={refetch} openFn={openFn} sysRole={updateSysRole} />
    </BaseContiner>;
};

export default SysRolePage;
